import { Table, TableProps, Tooltip, Image } from 'antd';
import { FormData } from '@/pages/historyReplay/components/SearchForm.tsx';
import { FC, useEffect, useState } from 'react';
import { keepPreviousData, useQuery } from '@tanstack/react-query';
import HistoryReplayServices from '@/api/services/historyReplayServices.ts';
import { useCatch } from '@/hooks';
import { Page } from '#/api.ts';
import { AlarmInfo } from '#/entity.ts';

type Props = {
  searchParams?: FormData;
};

const AlarmTable: FC<Props> = ({ searchParams }) => {
  const catchFn = useCatch();
  const [page, setPage] = useState<Page>({ page: 1, limit: 10, order: 'id DESC' });
  const [imageVisible, setImageVisible] = useState(false);
  const [imgList, setImgList] = useState<string[]>([]);

  useEffect(() => {
    if (searchParams) {
      setPage({
        page: 1,
        limit: 10,
        order: 'id DESC',
      });
    }
  }, [searchParams]);

  const { data: list, isFetching } = useQuery({
    placeholderData: keepPreviousData,
    queryKey: ['alarmList', searchParams, page],
    queryFn: () =>
      catchFn(() =>
        HistoryReplayServices.getAlarmList({
          plateNumber: searchParams!.plateNumber,
          startTime: searchParams!.startTime.format('YYYY-MM-DD HH:mm:ss'),
          endTime: searchParams!.endTime.format('YYYY-MM-DD HH:mm:ss'),
          page: page.page,
          limit: page.limit,
          order: page.order,
        }),
      ),
    select: ({ data, total }) => ({ data, total }),
    enabled: !!searchParams,
    staleTime: 0,
  });

  const tableProps: TableProps<AlarmInfo> = {
    size: 'small',
    columns: [
      { title: '病害类型', dataIndex: 'alarmDesc', align: 'left', width: 100, fixed: 'left' },
      { title: '报警时间', dataIndex: 'alarmTime', width: 190 },
      {
        title: '报警地点',
        dataIndex: 'alarmPosition',
        width: 500,
        ellipsis: true,
        render: (value) => {
          return <Tooltip title={value}>{value}</Tooltip>;
        },
      },
      {
        title: '现场照片',
        dataIndex: 'proof',
        align: 'right',
        fixed: 'right',
        width: 100,
        render: (_value, record) => {
          return (
            record.imageList.length > 0 && (
              <span
                style={{ color: 'var(--ycx-primary-color)' }}
                className="cursor-pointer text-xs"
                onClick={() => {
                  setImgList(
                    record.imageList.map((item) => `https://oss.uconcern.com/${item.fileUrl}`),
                  );
                  setImageVisible(true);
                }}
              >
                查看
              </span>
            )
          );
        },
      },
    ],
    dataSource: list?.data,
    pagination: {
      current: page.page,
      pageSize: page.limit,
      total: list?.total,
      showTotal: (total) => `共 ${total} 条数据`,
      onChange: (page, pageSize) => setPage({ page: page, limit: pageSize, order: 'id DESC' }),
    },
    scroll: {
      y: 140,
    },
    rowKey: 'id',
    loading: isFetching,
  };

  return (
    <>
      <Table {...tableProps} />
      <Image.PreviewGroup
        items={imgList}
        preview={{
          visible: imageVisible,
          onVisibleChange: (value) => {
            if (!value) {
              setImageVisible(value);
            }
          },
        }}
      />
    </>
  );
};

export default AlarmTable;
